import threading
from pymilvus import MilvusClient,DataType


class MilvusUtil:
    _instance = None
    _lock = threading.Lock() 
    
    def __init__(self):        
        url = "http://118.178.124.104:19530"
        self.client = MilvusClient(uri=url,db_name='default')             

    def __new__(cls, *args, **kwargs):
        if cls._instance:
            return cls._instance
        with cls._lock:
            cls._instance = super().__new__(cls)
            return cls._instance
    def createTable(self,table_name,dimension=1024):
        schema = MilvusClient.create_schema(
            auto_id=False,
            enable_dynamic_field=True,
        )

        # 3.2. Add fields to schema
        schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True)
        schema.add_field(field_name="vector", datatype=DataType.FLOAT_VECTOR, dim=dimension)
        
        # 3.3 准备索引parameters
        index_params = self.client.prepare_index_params()

        # 3.4 添加索引
        index_params.add_index(
            field_name="idx_id",
            index_type="STL_SORT"
        )

        index_params.add_index(
            field_name="idx_vector", 
            index_type="IVF_FLAT",
            metric_type="IP",
            params={ "nlist": 128 }
        )

        # 3.5 创建collection
        self.client.create_collection(
            collection_name= table_name,
            schema=schema,
            index_params=index_params
        )
        
    def insert(self,table_name,data):
        self.client.insert(collection_name=table_name,data=data)
    
    def upsert(self,table_name,data):
        self.client.upsert(collection_name=table_name,data=data)
        
    def search(self,table_name,query,limit=5,output_fields=['id','vector']):
        self.client.search(collection_name=table_name,data=query,limit=limit,output_fields=output_fields)
        
    def search(self,table_name,query,limit=5,output_fields=['id','vector'],search_filter)
        self.client.search(collection_name=table_name,data=query,limit=limit,output_fields=output_fields,search_params=search_filter)
        
    